import { defineComponent, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElButton,
  ElFormItem,
  ElInput,
  ElMessage,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElDatePicker
} from 'element-plus'
import AliIcon from '~/components/AliIocn'
import ExportExcel from '~/components/ExportExcel'
import styles from '../../event/data/index.module.scss'
import dayjs from 'dayjs'

export default defineComponent(function WorkData() {
  const store = useStore()
  const formValues = reactive<any>({
    keyWord: '',
    current: 1,
    size: 15
  })
  const state = reactive<any>({
    exportVisible: false,
    total: 0,
    list: [],
    sanMethod: [],
    sanMethod1: [],
    times: []
  })
  //  数据列表
  const index = async () => {
    const list: any[] = []
    state.sanMethod = []
    state.sanMethod1 = []
    try {
      const { data } = await store.dispatch('work/WorkDataListPageGet', formValues)
      data.records.forEach((item: any) => {
        if (item.loops.length > 0) {
          item.loops.forEach((row: any) => {
            if (row.lineRunDataList.length > 0) {
              row.lineRunDataList.forEach((el: any) => {
                const obj = {
                  ...el,
                  ...row,
                  ...item
                }
                list.push(obj)
              })
            }
          })
        }
      })
      //  计算合并列数据
      let count = 0
      for (let i = 0; i < list.length; i++) {
        if (i === 0) {
          state.sanMethod.push(1)
          count = 0
        } else {
          if (list[i].reportTime === list[i - 1].reportTime) {
            state.sanMethod[count] += 1
            state.sanMethod.push(0)
          } else {
            state.sanMethod.push(1)
            count = i
          }
        }
      }
      for (let i = 0; i < data.records.length; i++) {
        const item = data.records[i]
        for (let j = 0; j < item.loops.length; j++) {
          const row = item.loops[j]
          for (let z = 0; z < row.lineRunDataList.length; z++) {
            if (z === 0) {
              state.sanMethod1.push(row.lineRunDataList.length)
            } else {
              state.sanMethod1.push(0)
            }
          }
        }
      }
      state.list = list
      state.total = data.total
    } catch (error) {}
  }
  //  每页数量
  const onSizeChange = (value: any) => {
    formValues.size = value
    index()
  }
  //  分页
  const onCurrentChange = (value: any) => {
    formValues.current = value
    index()
  }
  const handleSearchList = () => {
    formValues.current = 1
    index()
  }
  //  时间限制
  const disabledDate = (time: any) => {
    const cur = new Date().getTime()
    const three = 30 * 24 * 3600 * 1000
    const threeMonths = cur - three
    return time.getTime() > Date.now() || time.getTime() < threeMonths
  }
  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') {
      if (formValues.keyWord!?.length < 3) {
        ElMessage.error('关键字输入太少，无法匹配到有效数据')
        return
      }
      index()
    }
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      index()
    }, 100)
  }
  //  合并表格
  const objectSpanMethod = ({ rowIndex, columnIndex }: any) => {
    if (columnIndex === 0) {
      const rowspan = state.sanMethod[rowIndex]
      const colspan = rowspan > 0 ? 1 : 0
      return {
        rowspan,
        colspan
      }
    }
    if (columnIndex === 1 || columnIndex === 2) {
      const rowspan = state.sanMethod1[rowIndex]
      const colspan = rowspan > 0 ? 1 : 0
      return {
        rowspan,
        colspan
      }
    }
  }
  // 打开导出弹框
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }
  onMounted(() => {
    formValues.beginReportTime = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss')
    formValues.endReportTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    state.times = [formValues.beginReportTime, formValues.endReportTime]
    index()
  })
  return () => {
    const props = {
      onChange: (value: any) => {
        if (value) {
          formValues.beginReportTime = value[0]
          formValues.endReportTime = value[1]
        } else {
          delete formValues.beginReportTime
          delete formValues.endReportTime
        }
        formValues.current = 1
        index()
      }
    }
    return (
      <ElCard>
        <div>
          <div class={styles['card-form']}>
            <ElFormItem key="keyWord" prop="keyWord" label="">
              <ElInput
                v-model={formValues.keyWord}
                placeholder="关键字"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>
            &nbsp;&nbsp;
            <ElFormItem key="times" prop="times">
              <ElDatePicker
                v-model={state.times}
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                disabled-date={disabledDate}
                {...props}
              />
            </ElFormItem>
            &nbsp;&nbsp;
            <ElButton
              type="primary"
              onClick={async () => {
                handleSearchList()
              }}
            >
              <AliIcon type="icon-sousuo" />
              &nbsp; 搜索
            </ElButton>
            <ElButton
              type="primary"
              plain
              onClick={async () => {
                handleSearchList()
              }}
            >
              <AliIcon type="icon-zhongzhi" />
              &nbsp; 重置
            </ElButton>
          </div>
        </div>
        <ElTable data={state.list} span-method={objectSpanMethod}>
          <ElTableColumn
            prop="reportTime"
            width={180}
            label="名称/日期"
            v-slots={{
              default: (scope: any) => (
                <>
                  <div>
                    <span>{scope.row.name}</span>
                    <br />
                    <span>{scope.row.reportTime}</span>
                  </div>
                </>
              )
            }}
          />
          <ElTableColumn
            prop="loopName"
            label="开关"
            v-slots={{
              default: (scope: any) => <span>{`K${scope.row.loopName}`}</span>
            }}
          />
          <ElTableColumn
            prop="diState"
            label="接触器"
            v-slots={{
              default: (scope: any) => <span>{scope.row.diState === 0 ? '断开' : '闭合'}</span>
            }}
          />
          <ElTableColumn prop="phase" label="线路/相位" />
          <ElTableColumn prop="voltage" label="电压(V)" />
          <ElTableColumn prop="current" label="电流(A)" />
          <ElTableColumn prop="activePower" label="有功功率(kW)" />
          <ElTableColumn prop="powerFactor" label="功率因数" />
          <ElTableColumn prop="leakageValue" label="漏电(A)" />
        </ElTable>
        <div style="height: 10px;"></div>
        <ElPagination
          v-model:currentPage={formValues.current}
          v-model:pageSize={formValues.size}
          layout="total, sizes, prev, pager, next, jumper"
          background={true}
          small={true}
          total={state.total}
          onSize-change={onSizeChange}
          onCurrent-change={onCurrentChange}
        />
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="equipment/DeviceExport"
            // columns={proSaasTableRef.value?.filterColumns}
            payload={{ params: formValues }}
            onCancel={handleChangeExportModal}
          />
        )}
      </ElCard>
    )
  }
})
